/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package test_system.user_logic;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import test_system.questions.TestWrapper;

/**
 *
 * @author root
 */
public class SessionSaver {

    private String[] userAnswer;
    private TestWrapper test;
    private User user;

    public SessionSaver(User user, TestWrapper test, String[] userAnswer) {
        this.user = user;
        this.test = test;
        this.userAnswer = userAnswer;
    }

    public void save() {
        StringBuffer saveContent = generateSaveContent();
        String fileName = user.getLogin() + ".txt";
        File file = new File(fileName);
        try {
            file.createNewFile();
            FileWriter wrt = new FileWriter(file);
            wrt.append(saveContent);
            wrt.flush();
            System.exit(0);
        } catch (IOException e) {
            System.out.println("there is some trouble with write-function");
            e.printStackTrace();
        }
    }

    private StringBuffer generateSaveContent() {
        StringBuffer writeInfo = new StringBuffer();
        writeInfo.append(user.toWrite());
        writeInfo.append("\n");
        writeInfo.append(test.toWrite());
        writeInfo.append("\n");
        writeInfo.append(userAnswersToString());
        return writeInfo;
    }

    private String userAnswersToString() {
        StringBuffer userAnsw = new StringBuffer();
        for (String answer : userAnswer) {
            userAnsw.append(answer);
            userAnsw.append(",");
        }
        return userAnsw.toString();
    }
}
